package at.ac.tuwien.mg.webservice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.task.Task;

import at.ac.tuwien.mg.Activiti;
import at.ac.tuwien.mg.bean.Offer;

@Path("/offerListener")
public class OfferListener {
	
	Activiti activiti = new Activiti();
	
	@POST
	@Path("receiveOffer")
	@Produces(MediaType.APPLICATION_XML)
	public void getOffer(Offer offer) {
		System.out.println("offerListener" + " >> received offer from supplier: " + offer.getSupplier().getName());
		System.out.println("trying to marshal offer");
		
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("offer", offer);
		
		
		RuntimeService runtimeService = activiti.getRuntimeService();
		Execution msgExec = runtimeService.createExecutionQuery().processInstanceId(offer.getProcessInstanceId()).messageEventSubscriptionName("newOfferReceived").singleResult();
		System.out.println("msgExec: " + msgExec);
		runtimeService.messageEventReceived("newOfferReceived", msgExec.getId(), map);
		
		System.out.println("offer marshaled and sent per message");
	}
	
	@GET
	@Path("test")
	@Produces(MediaType.TEXT_PLAIN)
	public String test() {
		
		//Test if we can access the right activiti data here
		TaskService taskservice = activiti.getTaskService();
		List<Task> tasks = taskservice.createTaskQuery().list();
		
		for(Task t : tasks)
			System.out.println(t.getId());
			
		return "worked!";
	}

}
